%% Author: vivimice
%% Created: Feb 3, 2012
%% Description: TODO: Add description to tstring
-module(tchar).

%%
%% Include files
%%
-include("tchar.hrl").

%%
%% Exported Functions
%%
-export([new/2, new_mb/1, new_ansi/1, to_binary/1, value_of/1]).
-export([equals/2]).

%%
%% API Functions
%%

% create new tchar, Type must be ansi or mb
new(Type, Value) ->
	case Type of
		ansi when is_number(Value), Value >= 0, Value < 128 ->
			#tchar{type=ansi, value=Value, width=1};
		ansi when is_list(Value), erlang:length(Value) == 1 ->
			[Head|_Rest] = Value,
			#tchar{type=ansi, value=Head, width=1};
		mb when is_binary(Value), byte_size(Value) == 2 ->
			#tchar{type=mb, value=Value, width=2};
		_ ->
			erlang:error({badarg, Type, Value})
	end.

new_ansi(CharValue) ->
	new(ansi, CharValue).

new_mb(Binary) ->
	new(mb, Binary).

value_of(Char) when erlang:is_number(Char), Char band 16#f0 == 0 ->
	new_ansi(Char);
value_of(Binary) when erlang:is_binary(Binary), erlang:byte_size(Binary) == 2 ->
	new_mb(Binary).

%% get binary of TChar or list of TChar (TChar String)
to_binary(TChar) when ?IS_TCHAR(TChar) ->
	Type = TChar#tchar.type,
	case Type of
		ansi -> 
			Value = TChar#tchar.value,
			<<Value>>;
		mb -> 
			TChar#tchar.value;
		_ -> 
			erlang:error(badarg)
	end.

%% compare to tchar or tchar list.
equals(TChar1, TChar2) when ?IS_TCHAR(TChar1), ?IS_TCHAR(TChar2) ->
	((TChar1#tchar.type) == (TChar2#tchar.type)) andalso 
		((TChar1#tchar.value) == (TChar2#tchar.value)).

%%
%% Local Functions
%%

